package ru.hh.team02.chat.utils;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class StringSocket {
    private Socket socket;
    
    private ObjectInputStream in;
    private ObjectOutputStream out;
    
    public StringSocket(Socket socket) {
        this.socket = socket;
        try {
            openStreams();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public String read() throws IOException {
        try {
            return (String)in.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }
    
    public void write(String message) throws IOException {
        out.writeObject(message);
        out.flush();
    }
    
    public ObjectOutputStream getWriter() {
        return out;
    }
    
    public boolean available() throws IOException {
        return socket.getInputStream().available() > 0;
    }
    
    public void close() {     
        try {
            out.close();
        } catch (IOException ioException1) {
            ioException1.printStackTrace();
        } finally {
            try {
                in.close();
            } catch(IOException ioException2) {
                ioException2.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e3) {
                    e3.printStackTrace();
                }
            }
        }
    }
    
    private void openStreams() throws IOException {
        out = new ObjectOutputStream(socket.getOutputStream());
        out.flush();
        in = new ObjectInputStream(socket.getInputStream());
    }
    
}